package com.woyowodaows.activity.mine;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.woyowodaows.R;
import com.woyowodaows.base.BaseActivity;
import com.woyowodaows.base.BaseBean;
import com.woyowodaows.base.ImageDataBean;
import com.woyowodaows.bean.home.NewNoticeBean;
import com.woyowodaows.bean.home.NewNoticeData;
import com.woyowodaows.bean.mine.CityBean;
import com.woyowodaows.bean.mine.CountyBean;
import com.woyowodaows.bean.mine.ProvinceBean;
import com.woyowodaows.bean.mine.ProvinceListData;
import com.woyowodaows.popupwind.ChoosePicWindow;
import com.woyowodaows.request.HttpAsyncTask;
import com.woyowodaows.request.HttpRequestListener;
import com.woyowodaows.request.InterfaceUrl;
import com.woyowodaows.utils.DisplayUtils;
import com.woyowodaows.utils.GlideImageLoader;
import com.woyowodaows.utils.PicassoImageLoader;
import com.woyowodaows.utils.RegularUtils;
import com.woyowodaows.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2019/3/28.
 * 新增报销单
 */

public class NewAddServiceActivity extends BaseActivity {
    @BindView(R.id.et_service_infos)
    EditText etServiceInfos;
    @BindView(R.id.et_service_detail)
    EditText etServiceDetail;
    @BindView(R.id.ll_password_old)
    LinearLayout llPasswordOld;
    @BindView(R.id.iv_updown)
    ImageView ivUpdown;
    @BindView(R.id.et_service_linkman)
    EditText etServiceLinkman;
    @BindView(R.id.et_service_phone)
    EditText etServicePhone;
    @BindView(R.id.tv_service_area)
    TextView tvServiceArea;
    @BindView(R.id.iv_choose_address)
    ImageView ivChooseAddress;
    @BindView(R.id.et_service_detailed_address)
    EditText etServiceDetailedAddress;
    @BindView(R.id.et_service_remark)
    EditText etServiceRemark;
    @BindView(R.id.btn_submit)
    Button btnSubmit;

    private String updownUrl="";
    private MyHandler myHandler = new MyHandler(this);
    //相册-相册
    String[] photo = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    private ChoosePicWindow popupwindow;
    private static final int REQUEST_CAMERA_CODE = 100;

    private ArrayList<ImageItem> imageItems;
    private File filesImg;

    private OptionsPickerView optionsPickerView;
    private List<ProvinceBean> options1Items = new ArrayList<>();
    private List<String> options1Item = new ArrayList<>();
    private List<List<String>> options2Item = new ArrayList<>();
    private List<List<List<String>>> options3Item = new ArrayList<>();
    private String mPickAddress;
    private int mOptions1, mOptions2, mOptions3;

    private String details = "";
    private boolean isSelect = false;//是否选择

    private int parentId=0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_new_add_service;
    }

    @Override
    protected void handleMessages(Message msg) {
        super.handleMessages(msg);
        if (msg.what == 3) {
            uploadMultipleImages(filesImg, imageItems);
        }
        if(msg.what == 0){
            initPickerView();
        }

    }


    @Override
    public void initView() {
        super.initView();
        ButterKnife.bind(this);
        setTitleBar(false, "新增报修", "", 0, 0, null);
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
    }

    @Override
    public void initData() {
        super.initData();
        getAddress();
    }
    private void getAddress() {
        Map<String, Object> mapParameter = new HashMap<>();
        HttpAsyncTask.getInstance().onPostParam(this, "...", false, InterfaceUrl.DISTRIBUTIONAREA, ProvinceListData.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    ProvinceListData bean = (ProvinceListData) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
                        options1Items.addAll(bean.getData());
                        if (options1Items != null && options1Items.size() > 0) {
                            for (int i = 0; i < options1Items.size(); i++) {
                                ProvinceBean provinceBean = options1Items.get(i);
                                options1Item.add(provinceBean.getName());
                                List<String> cityList = new ArrayList<>();  //该省的城市列表
                                List<List<String>> p_areaList = new ArrayList<>(); //该省的所有地区列表
                                for (int j = 0; j < provinceBean.getChild().size(); j++) {
                                    CityBean cityBean = provinceBean.getChild().get(j);
                                    String cityName = cityBean.getName();
                                    cityList.add(cityName);
                                    List<String> c_areaList = new ArrayList<>(); //该城市的所有地区
                                    if (options1Items.get(i).getChild().get(j).getChild() == null || options1Items.get(i).getChild().get(j).getChild().size() == 0) {
                                        c_areaList.add("");
                                    } else {
                                        for (int k = 0; k < cityBean.getChild().size(); k++) {
                                            CountyBean countyBean = cityBean.getChild().get(k);
                                            String countyName = countyBean.getName();
                                            c_areaList.add(countyName);
                                        }

                                    }
                                    p_areaList.add(c_areaList);
                                }
                                options2Item.add(cityList);
                                options3Item.add(p_areaList);

                            }
                        }
                    }
                }
                if(options1Items.size() > 0){
                    Message.obtain(myHandler, 0).sendToTarget();
                }
            }

            @Override
            public void onError(String message) {
                ToastUtil.show_short(mContext, message);
            }
        });
    }



    @OnClick({R.id.iv_updown, R.id.tv_service_area, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_updown://上传图片
                choosePhone();
                break;
            case R.id.tv_service_area://选择地址
                if(options1Items.size() > 0){
                    isSelect=true;
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(tvServiceArea.getWindowToken(), 0);
                    optionsPickerView.show();
                }else {
                    ToastUtil.show(mContext,"暂无数据");
                }
                break;
            case R.id.btn_submit://提交
                setUpData();
                DisplayUtils.closeKeybord(view,this);//关闭软键盘
                break;
        }
    }

    private void setUpData() {//创建报修单
        Map<String, Object> mapParameter = new HashMap<>();
//                title=报修&
//                detail=坏了
//                &contacts=张三
//                &phone=15855562221&
//                distributionAreaId=11&
//                distributionArea=宜春职业技术学院-南校区&
//                address=b5栋男宿舍&
//                remark=请尽快过来

        String title = etServiceInfos.getText().toString().trim();
        String detail = etServiceDetail.getText().toString().trim();
        String phone = etServicePhone.getText().toString().trim();
        String name = etServiceLinkman.getText().toString().trim();
        String chooseAddrees = tvServiceArea.getText().toString().trim();
        String detailedAddress = etServiceDetailedAddress.getText().toString().trim();
        String remark = etServiceRemark.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            ToastUtil.show(mContext, "输入故障信息标题不能为空");
            return;
        }
        if (TextUtils.isEmpty(detail)) {
            ToastUtil.show(mContext, "输入故障信息详情不能为空");
            return;
        }
//        if (TextUtils.isEmpty(updownUrl)) {
//            ToastUtil.show(mContext, "请上上传图片");
//            return;
//        }
        if (TextUtils.isEmpty(name)) {
            ToastUtil.show(mContext, "输入的名字不能为空");
            return;
        }

        if (TextUtils.isEmpty(phone)) {
            ToastUtil.show(mContext, "请输入手机号码");
            return;
        }

        if (!RegularUtils.getInstate().rehularPhone(phone)) {
            ToastUtil.show(mContext, "请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(chooseAddrees)) {
            ToastUtil.show(mContext, "请选择地址");
            return;
        }
        if (TextUtils.isEmpty(detailedAddress)) {
            ToastUtil.show(mContext, "请输入详细的地址");
            return;
        }
//        if (TextUtils.isEmpty(remark)) {
//            ToastUtil.show(mContext, "请输入备注");
//            return;
//        }

        mapParameter.put("title", title);
        mapParameter.put("detail", detail);
        mapParameter.put("contacts", name);
        mapParameter.put("phone", phone);
        mapParameter.put("distributionAreaId", parentId+"");
        mapParameter.put("distributionArea", chooseAddrees+"");
        mapParameter.put("address", detailedAddress);
        mapParameter.put("remark", remark+"");
        mapParameter.put("pic",updownUrl+"");

        HttpAsyncTask.getInstance().onPostParam(mContext, "", false, InterfaceUrl.REPAIRSAVE, BaseBean.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    BaseBean bean = (BaseBean) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
                            finish();
                            ToastUtil.show(mContext, bean.getMessage());
                    }
                }
            }

            @Override
            public void onError(String message) {
            }
        });

    }

    private void choosePhone() {
        if (popupwindow == null) {
            popupwindow = new ChoosePicWindow(this, tvTitle, "0");// 0显示一个按钮
        }
        popupwindow.showPopupWindow();
        popupwindow.setOnItemClickListener(new ChoosePicWindow.OnItemClickListener() {
            @Override
            public void onTake() {
                if (EasyPermissions.hasPermissions(mContext, photo)) {//检查是否获取该权限
                    openCamera();
                } else {
                    EasyPermissions.requestPermissions(this, "应用需要获取相机拍照和获取相册权限!", 1, photo);
                }
                popupwindow.hidePopupWindow();
            }

            @Override
            public void onChoose() {
                if (EasyPermissions.hasPermissions(mContext, photo)) {//检查是否获取该权限
                    openPhoto();
                } else {
                    EasyPermissions.requestPermissions(this, "应用需要获取相机拍照和获取相册权限!", 1, photo);
                }
                popupwindow.hidePopupWindow();
            }
        });
    }


    /**
     * 打开相机
     */
    private void openCamera() {
//        ImagePicker imagePicker = ImagePicker.getInstance();
//        imagePicker.setCrop(false);
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
        intent.putExtra("CropType", "6");//裁剪状态
        startActivityForResult(intent, REQUEST_CAMERA_CODE);
    }

    /**
     * 打开相册
     */
    private void openPhoto() {
//        ImagePicker imagePicker = ImagePicker.getInstance();
//        imagePicker.setCrop(false);

        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra("CropType", "6");//裁剪状态
        startActivityForResult(intent, REQUEST_CAMERA_CODE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            ImageItem bean = imageItems.get(0);
            if (imageItems != null && imageItems.size() > 0) {
                if (filesImg == null) {
                    filesImg = new File(bean.path);
                }
                filesImg = new File(bean.path);
                Message.obtain(myHandler, 3).sendToTarget();
                //  Log.i("zys",filesImg.toString());
            } else {
                ToastUtil.show(mContext, "获取照片失败,请重试！");
            }
        }
    }

    /**
     * 上传多张图片
     */
    public void uploadMultipleImages(File files, final ArrayList<ImageItem> imageItems) {
//        File fileImge=new File(videoFirstImagePath);
        showProgressDialog(mContext, "上传中...");
        Map<String, Object> mapParameter = new HashMap<>();
        HttpAsyncTask.getInstance().onPostFile(mContext, "", false, files, mapParameter, ImageDataBean.class, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    ImageDataBean bean = (ImageDataBean) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
//                        updownUrl = bean.getData().getStrFileName();
                        if (bean != null && bean.getData().size() > 0) {
                            updownUrl = bean.getData().get(0).getPath();
                        }
                        setImageAdapterData(bean.getData().get(0).getVisitUrl());
                    } else {
                        ToastUtil.show(mContext, bean.getMessage());
                    }
                    dismissProgressDialog();
                }
            }

            @Override
            public void onError(String message) {
                dismissProgressDialog();
                ToastUtil.show(mContext, message);
            }
        });
    }

    public void setImageAdapterData(String url) {//ArrayList<ImageItem> imageItems

        if (imageItems != null && imageItems.size() > 0) {

            Glide.with(mContext)
                    .load(url)
                    .placeholder(R.mipmap.default_image)
                    .error(R.mipmap.default_image)
                    .into(ivUpdown);
        }
    }
    private void initPickerView() {
        optionsPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                mPickAddress = options1Item.get(options1) + " "
                        + options2Item.get(options1).get(options2) + " "
                        + options3Item.get(options1).get(options2).get(options3);
                  if(options1Items.get(options1).getChild().get(options2).getChild().size()>0){
                      parentId=options1Items.get(options1).getChild().get(options2).getChild().get(options3).getParentId();
                  }else {
                      parentId=options1Items.get(options1).getChild().get(options2).getParentId();
                  }

//
//
// provinceText=options1Item.get(options1).getName();//省份
//                cityContent=options2Item.get(options1).get(options2);//城市
//                countyContent=options3Item.get(options1).get(options2).get(options3);//区
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        TextView sure = (TextView) v.findViewById(R.id.tv_finish);
                        TextView cancel = (TextView) v.findViewById(R.id.iv_cancel);
                        sure.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                optionsPickerView.returnData();
                                optionsPickerView.dismiss();
                                tvServiceArea.setText(mPickAddress);
                            }
                        });
                        cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                optionsPickerView.dismiss();
                            }
                        });
                    }
                })
                .setLineSpacingMultiplier(3.5f)
                .setContentTextSize(20)
                .setSelectOptions(mOptions1, mOptions2, mOptions3)
                .build();
        optionsPickerView.setPicker(options1Item, options2Item, options3Item);


    }


}